package com.feiwo.nonego.rpc.loadbalancer.sourceip.hash;

import com.feiwo.nonego.rpc.common.util.StringUtils;
import com.feiwo.nonego.rpc.loadbalancer.api.ServiceLoadBalancer;
import com.feiwo.nonego.rpc.spi.annotation.SPIClass;

import java.util.List;

/**
 *
 *
 * @author feiwo 2025-08-19
 */
@SPIClass
public class SourceIpHashServiceLoadBalancer<T> implements ServiceLoadBalancer<T> {
    @Override
    public T select(List<T> servers, int hashCode, String sourceIp) {
        if (servers == null || servers.isEmpty()) {
            return null;
        }
        if (StringUtils.isEmpty(sourceIp)) {
            return servers.get(0);
        }
        hashCode = Math.abs(sourceIp.hashCode() + hashCode);
        return servers.get(hashCode % servers.size());
    }
}
